package com.jielin.handling.service.casegoods.impl;

import com.amazonaws.services.s3.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.entity.casegoods.CaseGoods;
import com.jielin.handling.entity.casegoods.CaseGoodsAuditResult;
import com.jielin.handling.entity.vo.AllGoodsVo;
import com.jielin.handling.entity.vo.GoodsAmountVo;
import com.jielin.handling.entity.vo.GoodsStateVo;
import com.jielin.handling.entity.vo.PoliceVo;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.casegoods.CaseGoodsAuditResultMapper;
import com.jielin.handling.mapper.goods.BelongingsMapper;
import com.jielin.handling.service.accesspath.AccessPathService;
import com.jielin.handling.service.tsuspect.TSuspectService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.StringUtil;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jielin.handling.mapper.casegoods.CaseGoodsMapper;
import com.jielin.handling.service.casegoods.CaseGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Decoder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CaseGoodsServiceImpl implements CaseGoodsService {
	@Autowired
	XskyService xskyService;

	@Autowired
	CaseGoodsMapper caseGoodsMapper;

	@Autowired
	BelongingsMapper belongingsMapper;

	@Autowired
	CaseGoodsAuditResultMapper caseGoodsAuditResultMapper;

	@Autowired
	AccessPathService accessPathService;

	@Autowired
	TSuspectService tSuspectService;



	@Override
	public List<GoodsAmountVo> selectGoodsAmountByCaseCode(GoodsAmountVo vo) {
		log.info("vo:{}", vo);
		List<GoodsAmountVo> list = null;
		try {
			boolean power = accessPathService.findPowerIsBig(vo.getPoliceId());
			PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
			if(power){
				list = caseGoodsMapper.selectGoodsAmountByCaseCode(vo);
			}else{
				//只能查询自己的
				PoliceVo policeVo = tSuspectService.selectPolice(vo.getPoliceId());
				vo.setPoliceCode(policeVo.getPoliceCode());
				list = caseGoodsMapper.selectGoodsAmountByCaseCode(vo);
			}
			int j = 0;
			for(GoodsAmountVo vos:list){
				//根据案件编号查询案件下面的所有的案件数量
				Integer i=caseGoodsMapper.selectGoodsCount(vos.getCaseCode());
				if(i==null){
					i=0;
					vos.setAmount(i);
				}else{
					list.get(j).setAmount(i);
				}
                j++;
			}
		} catch (Exception e) {
			log.error("查询异常={}", e);
		}
		return list;
	}

	@Override
	public List<GoodsStateVo> selectGoodsTypeByCaseCode(String caseCode,int pageNum,int pageSize) {

		log.info("caseCode:{}", caseCode);
		List<GoodsStateVo> list = null;
		try {
			PageHelper.startPage(pageNum, pageSize);
			list = caseGoodsMapper.selectGoodsTypeByCaseCode(caseCode);
		} catch (Exception e) {
			log.error("查询异常={}", e);
		}
		return list;
	}

	@Override
	public List<AllGoodsVo> selectAllGoods(AllGoodsVo vo) {
		log.info("vo:{}", vo);
		List<AllGoodsVo> list = null;
		try {
			PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
			list = caseGoodsMapper.selectAllGoods(vo);
		} catch (Exception e) {
			log.error("查询异常={}", e);
		}
		return list;
	}

	@Override
	@Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
	public int updateGoodsById(CaseGoodsAuditResult vo) {
		int i=0;
		try {
		String array[]=vo.getIds().split(",");
		for(String goodsId:array){
			vo.setGoodsId(goodsId);
            //修改物品状态
			caseGoodsMapper.updateGoodsById(vo);
			i++;
		}
		}catch (Exception e){
			log.info("service 事务回滚:{}",e);
			//抛出异常让其回滚
			throw new RuntimeException("事务回滚");
		}
		return i;
	}


	@Override
	public int revokeGoodsById(AllGoodsVo vo) {
		int i=0;
		String array[]=vo.getIds().split(",");
		for(String id:array){
			vo.setId(id);
			caseGoodsMapper.revokeGoodsById(vo);
			i++;
		}
		return i;
	}



	@Override
	public int insertSelective(CaseGoods vo) {
		int i=0;

		String fileName = DateUtil.getNumberFormatDate()+".png";

		String imgFilePath = GenerateImage(vo.getPicUrl(), fileName);
		if(imgFilePath==null){
			return 0;
		}
		//使用XSKY存储路径
		if (ConstantUtil.XSKYRESTORAGE) {
			vo.setPicUrl(ConstantUtil.XSKY_PHOTO_URL+imgFilePath);
		}else{
			//不使用XSKY存储路径
			vo.setPicUrl(ConstantUtil.SERVER_URL+ File.separator+"suspect"+ File.separator+"goods"+File.separator+fileName);
		}
		String pmId = vo.getCorrelationOrgId();


		//根据警员id查询机构号
		Map<String,Object>map =caseGoodsMapper.selectJgh(pmId);
		//设置机构号
		vo.setCorrelationOrgId(map.get("id").toString());
		//设置添加民警姓名和编号
		vo.setPoliceAndCode(map.get("name").toString()+"/"+map.get("police_code"));

        //新增物品
		i=caseGoodsMapper.insertSelective(vo);

		CaseGoodsAuditResult caseGoodsAuditResult= new CaseGoodsAuditResult();
        //新增审核记录 默认为未审核
		caseGoodsAuditResult.setId(StringUtil.generatorUUID());//审核id
		caseGoodsAuditResult.setGoodsId(vo.getId());//物品id
		caseGoodsAuditResult.setApplyPolice(map.get("police_code").toString());//警员号
		caseGoodsAuditResult.setFindingsOfAudit("0");//审核状态
		caseGoodsAuditResult.setGoodsWarehousing("1101");// 涉案财物入库借出状态(1101.初始入库,1102,借出,1103.归还入库1104.送检,1105移交,1106.销毁,1107拍卖,1108.上缴国库)
		caseGoodsAuditResult.setIsNew("1");// 是否是最新记录(0.不是,1.是)
		caseGoodsAuditResultMapper.insertSelective(caseGoodsAuditResult);
		return i;
	}

	public  String GenerateImage(String imgStr, String photoname) {
		//对字节数组字符串进行Base64解码并生成图片
		//图像数据为空
		if (imgStr == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			//Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					//调整异常数据
					b[i] += 256;
				}
			}
			String folderPath = ConstantUtil.PHOTO_PATH+"suspect"+ File.separator+"goods"+File.separator;
			String imgFilePath = folderPath + photoname;

			//判断是否使用XSKY存储
			if (ConstantUtil.XSKYRESTORAGE) {
				try {
					ObjectMetadata meta = new ObjectMetadata();
					meta.setContentType(ContentType.IMAGE_JPEG.getMimeType());
					xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, imgFilePath, b, meta);
				} catch (Exception e) {
					log.error(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
					return null;
				}
			}else{
				OutputStream out = new FileOutputStream(imgFilePath);
				out.write(b);
				out.flush();
				out.close();
			}
			return imgFilePath;
		} catch (Exception e) {
			return null;
		}
	}


	@Override
	public int deleteByPrimaryKey(String id) {
		int i=0;
		i=caseGoodsMapper.deleteByPrimaryKey(id);
		return i;
	}
    //更新涉案物品
	@Override
	@Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
	public int updateByPrimaryKeySelective(CaseGoods vo) {
		try {


			//判断图片是否已经存在
			if(vo.getPicUrl() != "" && vo.getPicUrl() != null  ){
				String fileName = DateUtil.getNumberFormatDate()+".png";
				String imgFilePath = GenerateImage(vo.getPicUrl(), fileName);
				if (ConstantUtil.XSKYRESTORAGE) {
					vo.setPicUrl(ConstantUtil.XSKY_PHOTO_URL + imgFilePath);
				}else{
					//不使用XSKY存储路径
					vo.setPicUrl(ConstantUtil.SERVER_URL+ File.separator+"suspect"+ File.separator+"goods"+File.separator+fileName);
				}
			}
             //设置审核原因需要的字段
			CaseGoodsAuditResult caseGoodsAuditResult=new CaseGoodsAuditResult();
		caseGoodsAuditResult.setFindingsOfAudit(vo.getFindingsOfAudit());
		caseGoodsAuditResult.setReasonsForFailure(vo.getReasonsForFailure());
		caseGoodsAuditResult.setGoodsId(vo.getId());
		//修改审核原因
		caseGoodsAuditResultMapper.updateByPrimaryKeySelective(caseGoodsAuditResult);
		//修改物品信息
		return caseGoodsMapper.updateByPrimaryKeySelective(vo);
		}catch (Exception e){
			log.info("service 事务回滚:{}",e);
			//抛出异常让其回滚
			throw new RuntimeException("事务回滚");
		}
	}

	@Override
	public CaseGoods selectGoodsById(String id) {
		return caseGoodsMapper.selectGoodsById(id);
	}

	@Override
	public List<GoodsAmountVo> selectGoods(GoodsAmountVo vo) {
		List<GoodsAmountVo> list=null;
		//查询角色是否管理员true为管理员false警员
		boolean power = accessPathService.findPowerIsBig(vo.getPoliceId());

		//如果为管理员查询所有
		if(power){
			PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
			list= caseGoodsMapper.selectGoods(vo);
		}else{
			//只能查询自己的
			PoliceVo policeVo = tSuspectService.selectPolice(vo.getPoliceId());
			vo.setApplyPolice(policeVo.getPoliceCode());
			PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
			list= caseGoodsMapper.selectGoods(vo);
		}

		return list;
	}



}
